import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import UserInfo from '../views/UserInfo.vue'
import TalkView from '../views/TalkView.vue'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },{
    path: '/home/:id',
    name: 'home',
    component: HomeView
  },{
    path: '/userInfo/:id',
    name: 'user',
    component: UserInfo
  },{
    path: '/talk/:from/:to',
    name: 'talk',
    component: TalkView
  },{
    path: '/Login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/LoginView.vue')
  },{
    path: '/logon',
    name: 'logon',
    component: () => import(/* webpackChunkName: "not" */ '../views/LoginOn.vue')
  },{
    path: '*',
    name: 'not',
    component: () => import(/* webpackChunkName: "not" */ '../views/NotFind.vue')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 如果没登录，跳转到登录页面
router.beforeEach((to, from, next) => {
  if(to.name !== 'login') {
    let user = localStorage.getItem('user');
    if(!user) {
      Message({ message: '未登陆！', type: 'error', duration: 5 * 1000, showClose: false, dangerouslyUseHTMLString: true })
      next({name: 'login'});
    } else {
      next()
    }
  } else {
    next()
  }
  
})

export default router
